package com.example.service.impl;

import com.example.common.constant.ResultCode;
import com.example.common.exception.ServiceException;
import com.example.domain.dto.LoginDTO;
import com.example.common.security.JwtTokenProvider;
import com.example.service.AuthService;
import com.example.service.LoginLogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenProvider tokenProvider;
    private final LoginLogService loginLogService;
    private final HttpServletRequest request;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Override
    public String login(LoginDTO loginDTO) {
        try {
            // 验证用户名密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginDTO.getUsername(),
                            loginDTO.getPassword()
                    )
            );

            // 保存认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 记录登录日志
            loginLogService.recordLoginLog(loginDTO.getUsername(), "1", "登录成功", request);

            // 生成token
            return tokenProvider.generateToken(authentication);
        } catch (AuthenticationException e) {
            // 记录登录日志
            loginLogService.recordLoginLog(loginDTO.getUsername(), "0", "密码错误", request);
            if (e.getMessage().contains("User is disabled")) {
                throw new ServiceException(ResultCode.USER_DISABLED);
            }
            throw new ServiceException(ResultCode.PASSWORD_ERROR);
        }
    }

    @Override
    public void logout() {
        SecurityContextHolder.clearContext();
    }
} 